using System;

namespace IgorPavlov.SevenZip.Core.Compression.LZMA.enc
{
    sealed class LenPriceTableEncoder : LenEncoder
    {
        UInt32 _tableSize;
        private readonly UInt32[] _prices = new UInt32[Base.kNumLenSymbols << Base.kNumPosStatesBitsEncodingMax];
        private readonly UInt32[] _counters = new UInt32[Base.kNumPosStatesEncodingMax];

        public void SetTableSize(UInt32 tableSize) { _tableSize = tableSize; }

        public UInt32 GetPrice(UInt32 symbol, UInt32 posState)
        {
            return _prices[posState * Base.kNumLenSymbols + symbol];
        }

        void UpdateTable(UInt32 posState)
        {
            SetPrices(posState, _tableSize, _prices, posState * Base.kNumLenSymbols);
            _counters[posState] = _tableSize;
        }

        public void UpdateTables(UInt32 numPosStates)
        {
            for (UInt32 posState = 0; posState < numPosStates; posState++)
                UpdateTable(posState);
        }

        public new void Encode(RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
        {
            base.Encode(rangeEncoder, symbol, posState);

            if (--_counters[posState] == 0)
                UpdateTable(posState);
        }
    }
}
